package com.zy.openchat.util;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;


import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MediaStoreCompat {
    public static final String PREFIX_EXTRA = "EXTRA_";//Intent数据前缀
    //已选择的多媒体数据列表
    public static final String EXTRA_PICKED_MEDIA_LIST = PREFIX_EXTRA + "picked_media_list";

    private final WeakReference<Context> mContext;
    private CaptureStrategy mCaptureStrategy;
    private String mCurrentPhotoPath;
    private Uri mCurrentPhotoUri;
    private String mCurrentVideoPath;

    public MediaStoreCompat(Context context) {
        mContext = new WeakReference<>(context);
    }

    /**
     * Checks whether the device has a camera feature or not.
     *
     * @param context a context to check for camera feature.
     * @return true if the device has a camera feature. false otherwise.
     */
    public static boolean hasCameraFeature(Context context) {
        PackageManager pm = context.getApplicationContext().getPackageManager();
        return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }

    public void setCaptureStrategy(CaptureStrategy strategy) {
        mCaptureStrategy = strategy;
    }

    public Intent dispatchCaptureImageIntent(Context context) {
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (captureIntent.resolveActivity(context.getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createMediaFile(true);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (photoFile != null) {
                mCurrentPhotoPath = photoFile.getAbsolutePath();
                mCurrentPhotoUri = FileProvider.getUriForFile(mContext.get(),
                        mCaptureStrategy.authority, photoFile);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoUri);
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    List<ResolveInfo> resInfoList = context.getPackageManager()
                            .queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        context.grantUriPermission(packageName, mCurrentPhotoUri,
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                }
            }
        }
        return captureIntent;
    }

    public Intent dispatchCaptureVideoIntent(Context context) {
        Intent captureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (captureIntent.resolveActivity(context.getPackageManager()) != null) {
            File videoFile = null;
            try {
                videoFile = createMediaFile(false);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (videoFile != null) {
                mCurrentVideoPath = videoFile.getAbsolutePath();
                Uri mCurrentVideoUri = FileProvider.getUriForFile(mContext.get(),
                        mCaptureStrategy.authority, videoFile);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentVideoUri);
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    List<ResolveInfo> resInfoList = context.getPackageManager()
                            .queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        context.grantUriPermission(packageName, mCurrentVideoUri,
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                }
                captureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);    // MediaStore.EXTRA_VIDEO_QUALITY 表示录制视频的质量，从 0-1，越大表示质量越好，同时视频也越大
                captureIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, mCaptureStrategy.limitDuration);   // 设置视频录制的最长时间
            }
        }
        return captureIntent;
    }



    public String onActivityResultForImage(Intent data) {
        Uri contentUri = mCurrentPhotoUri;
        String path = mCurrentPhotoPath;

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            mContext.get().revokeUriPermission(contentUri,
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

        new SingleMediaScanner(mContext.get().getApplicationContext(), path, new SingleMediaScanner.ScanListener() {
            @Override
            public void onScanFinish() {
                Log.i("SingleMediaScanner", "scan finish!");
            }
        });
        return path;
    }

    public String onActivityResultForVideo(Intent data) {
        Uri contentUri = data.getData();

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
            mContext.get().revokeUriPermission(contentUri,
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

        new SingleMediaScanner(mContext.get().getApplicationContext(), mCurrentVideoPath, new SingleMediaScanner.ScanListener() {
            @Override
            public void onScanFinish() {
                Log.i("SingleMediaScanner", "scan finish!");
            }
        });
        return mCurrentVideoPath;

    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    private File createMediaFile(boolean isImageType) throws IOException {
        // Create an image file name
        String timeStamp =
                new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String mediaFileName = String.format(isImageType?"JPEG_%s.jpg":"MP4_%s.mp4", timeStamp);
        File storageDir;
        if (mCaptureStrategy.isPublic) {
            storageDir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES);
            if (!storageDir.exists()) storageDir.mkdirs();
        } else {
            storageDir = mContext.get().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        if (mCaptureStrategy.directory != null) {
            storageDir = new File(storageDir, mCaptureStrategy.directory);
            if (!storageDir.exists()) storageDir.mkdirs();
        }

        // Avoid joining path components manually
        File tempFile = new File(storageDir, mediaFileName);

        // Handle the situation that user's external storage is not ready
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }

        return tempFile;
    }


    public static void playVideo(Context context, String filePath){
        if(TextUtils.isEmpty(filePath)){
            return;
        }
        File file = new File(Uri.decode(filePath));
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, "com.tsbc.ubabe.fileProvider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "video/*");
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context, "没有支持视频预览的应用", Toast.LENGTH_SHORT).show();
        }
    }

}
